﻿using StudentInformation_Demo.Database;
using StudentInformation_Demo.Models;
using StudentInformation_Demo.Services.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace StudentInformation_Demo.Services
{
    public class StudentServices : IStudentServices
    {
        private readonly PojectDatabase database;

        public StudentServices(PojectDatabase database)
        {
            this.database = database;
        }

        public void AddMajor(Major major)
        {
            database.Majors.Add(major);
        }

        public void AddStudent(Student model)
        {
            database.Students.Add(model);
        }

        public void DeleteStudent(int Id)
        {
            database.Students.Remove(GetStudent(Id));
        }

        public IEnumerable<Major> GetAllMajors()
        {
            return database.Majors.ToList();
        }

        public IEnumerable<Student> GetAllStudent(PageEntity page)
        {
            List<Student> students = null;
            students = database.Students.OrderBy(x => x.Id).ToList();
            if (students!=null && page !=null)
            {
                page.Total = students.Count;
                students = students
                    .Skip((page.PageIndex - 1) * page.PageSize)
                    .Take(page.PageSize)
                    .ToList();
            }
            return students;
        }

        public Major GetMajor(int Id)
        {
            return database.Majors.FirstOrDefault(x => x.Id == Id);
        }

        public Student GetStudent(int Id)
        {
            return database.Students.FirstOrDefault(x => x.Id == Id);
        }

        public bool Save()
        {
            return database.SaveChanges() > 0;
        }

        public IEnumerable<Student> SelectStudent(string queryStr)
        {
            return database.Students
                .Where(x => x.Name.Contains(queryStr) || x.SNo.Contains(queryStr))
                .ToList();
        }

        public void UpdateStudent(Student model)
        {
            var s = database.Students.FirstOrDefault(x => x.Id == model.Id);
            s.Gender = model.Gender;
            s.Birthday = model.Birthday;
            s.MId = model.MId;
            s.Email = model.Email;
            s.ImgPath = model.ImgPath;
            s.Name = model.Name;
            s.TelPhone = model.TelPhone;
            if (s!=null)
            {
                database.Students.Update(s);
            }
        }
    }
}
